﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace websocket.Controllers
{
    [AllowAnonymous]
    [Route("api/[controller]")]
    [ApiController]
    public class WebSocketController : ControllerBase
    {
        // GET: api/<WebSocketController>
        [AllowAnonymous]
        [HttpGet("/ws")]
        public async Task Get()
        {
            if (HttpContext.WebSockets.IsWebSocketRequest)
            {
                using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
               
                var serverMsg = Encoding.UTF8.GetBytes($"Server:Hello.Welcome! I'm WebSocket!");
                //发送到前台
                await webSocket.SendAsync(new ArraySegment<byte>(serverMsg, 0, serverMsg.Length), WebSocketMessageType.Text, true, CancellationToken.None);

                await Echo(webSocket);
            }
            else
            {
                HttpContext.Response.StatusCode = 400;
            }
        }

        private async Task Echo(WebSocket websocket)
        {
            var buffer = new byte[1024 * 4];//4k 大小
            
            var result = await websocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                var serverMsg = Encoding.UTF8.GetBytes($"Server:Hello.You side:{Encoding.UTF8.GetString(buffer)}");
                //发送到前台
                await websocket.SendAsync(new ArraySegment<byte>(serverMsg, 0, serverMsg.Length), result.MessageType,result.EndOfMessage, CancellationToken.None);
                result = await websocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                Debugger.Log(4, "websocket","Message received from Client");
            }
            await websocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }

        // GET api/<WebSocketController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<WebSocketController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<WebSocketController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<WebSocketController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
